import os
from os.path import isdir, join, dirname
import importlib

from fastapi import APIRouter

from utils.log import logger

router = APIRouter(prefix='/api')


def __auto_route_rule():
    """
    自动路由规则
    1. router = APIRouter() 这个定语在每个文件夹的index.py当中
    """


def __get_import_path(dir_path, filename):
    temp = dir_path.split('api')[-1].replace('/', '.').replace('\\', '.')
    while temp.startswith("."):
        temp = temp[1:]
    return f"api.{temp}.{filename[:-3]}"


def __get_routers(dir_path):
    """遍历目录并返回路由文件"""
    # logger.debug(dir_path)
    for filename in os.listdir(dir_path):
        if isdir(join(dir_path, filename)) and filename != '__pycache__':
            yield from __get_routers(join(dir_path, filename))
        else:
            if filename == 'index.py':
                import_path = __get_import_path(dir_path, filename)
                module = importlib.import_module(__get_import_path(dir_path, filename))
                if hasattr(module, 'router'):
                    logger.debug(f"加载 {import_path} 路由成功")
                    yield getattr(module, 'router')


for r in __get_routers(dirname(__file__)):
    # logger.debug(f"加载 {r} 路由成功")
    router.include_router(r)
